package com.lkcg.demo.config.auditor;

import com.lkcg.demo.model.base.BaseModel;
import com.lkcg.demo.utils.SpringContextUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Properties;

/**
 * 审计接口，自动注入用户id以及自动获取注入更新时间和创建时间
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class})})
@Component
public class AuditingInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        LocalDateTime currentDate = LocalDateTime.now();
        String currentUserId = SpringContextUtils.getBean(UserIDAuditorConfig.class)
                .getCurrentAuditor();

        if (SqlCommandType.UPDATE == sqlCommandType) {
            BaseModel auditingModel = (BaseModel) parameter;
            auditingModel.setUpdateBy(currentUserId);
            auditingModel.setUpdateDate(currentDate);
        } else if (SqlCommandType.INSERT == sqlCommandType) {
            BaseModel auditingModel = (BaseModel) parameter;
            auditingModel.setUpdateBy(currentUserId);
            auditingModel.setUpdateDate(currentDate);
            auditingModel.setCreateBy(currentUserId);
            auditingModel.setCreateDate(currentDate);

        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }
}